from flask import Flask, request, jsonify
import numpy as np
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# 初始化网络权重
def init_weights():
    """初始化4x2权重矩阵和2x1偏置向量"""
    weights = np.random.randn(4, 2) * 0.1  # 4x2权重矩阵
    bias = np.random.randn(2) * 0.1        # 2x1偏置向量
    return weights, bias

# 全局变量存储当前权重
weights, bias = init_weights()

@app.route('/predict', methods=['POST'])
def predict():
    """接收4维输入，返回2维输出"""
    try:
        data = request.json
        input_vector = np.array(data['input'])
        
        if len(input_vector) != 4:
            return jsonify({'error': '输入维度必须为4'}), 400
            
        # 前向传播计算
        output = np.dot(input_vector, weights) + bias
        
        return jsonify({
            'output': output.tolist(),
            'weights': weights.tolist(),
            'bias': bias.tolist()
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/reset_weights', methods=['POST'])
def reset_weights():
    """重新初始化网络权重"""
    global weights, bias
    weights, bias = init_weights()
    return jsonify({
        'message': '权重已重新初始化',
        'weights': weights.tolist(),
        'bias': bias.tolist()
    })

@app.route('/get_weights', methods=['GET'])
def get_weights():
    """获取当前权重"""
    return jsonify({
        'weights': weights.tolist(),
        'bias': bias.tolist()
    })

if __name__ == '__main__':
    app.run(debug=True, port=5000)
